package com.wuhunyu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.service.OssService;
import com.wuhunyu.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传业务层
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-01-15 22:04
 */
@Service("ossService")
public class OssServiceImpl implements OssService {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public CommonResult uploadFile(MultipartFile file) {
        // 校验file非空
        if (file == null) {
            return CommonResult.error("文件上传失败");
        }
        String endpoint = ConstantPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流
        InputStream inputStream = null;
        // 文件url
        String url = null;
        try {
            inputStream = file.getInputStream();
            // 文件上传完毕，手动拼接url
            // 以日期为文件夹
            String date = new DateTime().toString("yyyyMMdd");
            // 随机生成文件名称
            String suffix = file.getOriginalFilename().lastIndexOf(".") == -1 ? ".jpg" : file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = date + "/" + UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            /**
             * ConstantPropertiesUtils.BUCKET_NAME: bucket的名称
             * file.getOriginalFilename()：获取源文件的名称
             * inputStream：文件输入流
             */
            ossClient.putObject(ConstantPropertiesUtils.BUCKET_NAME, fileName, inputStream);
            url = ConstantPropertiesUtils.URL + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.error("文件上传失败");
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient
                ossClient.shutdown();
            }
        }
        // 封装结果
        Map<String, Object> map = new HashMap<>(16);
        map.put("url", url);
        return CommonResult.success("文件上传成功", map);
    }

}
